package com.shanzmoo.platform.tomember.api.config;

import com.shanzmoo.base.bean.SResponse;
import com.shanzmoo.base.constant.ErrorCode;
import com.shanzmoo.base.util.SResponseUtils;
import com.shanzmoo.platform.tomember.api.filter.JwtAuthenticationFilter;
import com.shanzmoo.platform.tomember.api.service.AuthUserDetailsService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsUtils;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    private static final String[] AUTH_WHITELIST = {
            // -- swagger ui
            "/swagger-ui.html",
            "/swagger-ui/*",
            "/swagger-resources/**",
            "/v2/api-docs",
            "/v3/api-docs",
            "/webjars/**",
            "/favicon.ico",
            "/swagger-ui",
            "/doc.html",
            "/cache/global/**",
            "/",
            "/csrf",
            "/error",
            // 登录 接口
            "/api/auth/*",
            "/auth/*",
            // 开发接口
            "/open/**"
    };
    private final JwtAuthenticationFilter jwtAuthenticationFilter;
    private final AuthUserDetailsService authUserDetailsService;

    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Bean
    public BCryptPasswordEncoder encoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(authUserDetailsService)
                .passwordEncoder(encoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 处理跨域问题， cores 预检放行，让Spring security 放行所有 preflight request (cors 预检请求)
        http.authorizeRequests().requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
        // 关闭HttpSession
        http.csrf().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().headers().cacheControl();

        // 配置 请求放行的url
        http.authorizeRequests()
                // 放行
                .antMatchers(AUTH_WHITELIST).permitAll()
                // 其他地址的访问均需验证权限
                .anyRequest().authenticated();

        // 添加自定义 JWT 过滤器, 拦截token
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置 异常处理器
        http.exceptionHandling()
                // 未授权处理器
                .accessDeniedHandler(getAccessDeniedHandler())
                // 未认证处理器
                .authenticationEntryPoint(getAuthenticationEntryPoint());

        // 关闭默认登录，由自己实现
        http.formLogin().disable()
                .httpBasic().disable();

        // 配置 退出处理器
//        http.logout().addLogoutHandler().logoutSuccessHandler();

    }

    /**
     *  未授权处理器
     * @return
     */
    @Bean
    public AccessDeniedHandler getAccessDeniedHandler() {
        return (request, response, accessDeniedException) -> {
            accessDeniedException.printStackTrace();
            SResponseUtils.outputJson(response, SResponse.fail(ErrorCode.NOT_AUTHORIZE));
        };
    }

    /**
     * 未认证处理器
     * @return
     */
    @Bean
    public AuthenticationEntryPoint getAuthenticationEntryPoint() {
        return (request, response, authenticationException) -> {
            authenticationException.printStackTrace();
            // 登录账号、密码验证失败
            if (authenticationException instanceof InsufficientAuthenticationException){
                SResponseUtils.outputJson(response, SResponse.fail(ErrorCode.TOKEN_INSUFFICIENT));
            } else {
                SResponseUtils.outputJson(response, SResponse.fail(ErrorCode.NOT_AUTH));
            }
        };
    }
}
